# coding: utf-8

import tornado
import json
import math
import datetime
from bson import ObjectId
from handlers.base import BaseHandler


class BloodSugarHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        try:
            rid = self.get_query_argument('rid')
        except Exception as err:
            self.response_msg(400, '参数错误')
            return
        #判断page是否存在
        skip = 0
        limit = 7
        results = []
        try:
            if 'page' in self.request.arguments:
                page = self.get_argument('page')
                if not page:
                    page = 1
                #返回对应page的list
                limit = 20
                skip = (int(page)-1)*limit
            #下面就是查询语句
            where = {}
            where['role'] = rid
            where['measureType'] = 'sugar'
            #限制返回字段
            fieldList = {}
            fieldList['_id'] = 1
            fieldList['sugarValue'] = 1
            fieldList['created_at'] = 1
            fieldList['advice'] = 1
            fieldList['timePoint'] = 1
            #组装语句
            listRes = self.db.HMMeasure.find(where,fieldList).sort('created_at',-1).skip(skip).limit(limit)
            while(yield listRes.fetch_next):
                tempObj = listRes.next_object()
                tempObj['objectId'] = str(tempObj['_id'])
                tempObj['created_at'] = tempObj['created_at'].strftime("%Y-%m-%d %H:%M")
                del tempObj['_id']
                 #获取建议
                if 'page' in self.request.arguments:
                    advice = yield self.db.HMMeasureAdvice.find_one({'_id': ObjectId(tempObj['advice'])})
                    tempObj['adviceStr'] = advice['diet']
                results.append(tempObj)
            self.response_msg(200,"获取成功",results)
        except Exception as e:
            print(e)
            self.response_msg(500,str(e))

    @tornado.gen.coroutine
    def post(self):
        try:
            rid = self.get_argument('rid')
            timePoint = self.get_argument('timePoint')
            created_at = self.get_argument('created_at')
            bloodSugarValue = self.get_argument('bloodSugarValue')
            bloodSugarValue = round(float(bloodSugarValue),1)
            created_at = datetime.datetime.strptime(created_at, '%Y-%m-%dT%H:%M:%S')
        except Exception as e:
            self.response_msg(400, '参数错误')
            return
        if timePoint == '空腹':
            if bloodSugarValue < 3.9:
                tag = '血糖偏低'
            elif bloodSugarValue >= 3.9 and bloodSugarValue <= 6.1:
                tag = '血糖适当'
            else:
                tag = '血糖偏高'
        elif timePoint == '餐后1小时':
            if bloodSugarValue < 11.1:
                tag = '血糖适当'
            else:
                tag = '血糖偏高'
        elif timePoint == '餐后2小时':
            if bloodSugarValue < 7.8:
                tag = '血糖适当'
            else:
                tag = '血糖偏高'
        elif timePoint == '其他时间':
            if bloodSugarValue < 7.8 and bloodSugarValue >= 2.8:
                tag = '血糖适当'
            elif bloodSugarValue >= 7.8:
                tag = '血糖偏高'
            elif bloodSugarValue < 2.8:
                tag = '血糖偏低'
        else:
            print('timePoint输入的有误')
        # 根据tag找出对应的advice
        advice = yield self.db.HMMeasureAdvice.find_one({'tag': tag})
        # 保存血糖的测量数据
        ret = yield self.db.HMMeasure.save({'role': rid, 'sugarValue': bloodSugarValue, 'created_at': created_at,
                                            'timePoint': timePoint, 'measureType': 'sugar', 'advice': str(advice['_id'])
                                      })
        self.response_msg(200, '保存成功', {'objectId': str(ret)})


        self.response_msg(400, '保存未成功')